<template>
  <el-container class="profile-container">
    <el-main>
      <el-card>
        <template #header>
          <h2>个人中心</h2>
        </template>

        <el-tabs v-model="activeTab" class="profile-tabs">
          <el-tab-pane label="基本资料" name="info">
            <div v-if="loadingProfile" class="tab-loading">
              <el-progress :percentage="50" :indeterminate="true" />
              <p>加载中...</p>
            </div>
            <el-form v-else-if="profileForm" ref="profileFormRef" :model="profileForm" :rules="profileRules" label-width="100px" style="max-width: 500px;">
              <el-form-item label="用户名">
                <el-input :value="currentUser.username" disabled />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input :value="currentUser.email" disabled />
              </el-form-item>
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="profileForm.nickname" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleUpdateProfile" :loading="updatingProfile">保存修改</el-button>
              </el-form-item>
            </el-form>
            <el-alert v-if="errorProfile" :title="errorProfile" type="error" show-icon :closable="false" />
          </el-tab-pane>

          <el-tab-pane label="修改密码" name="password">
            <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="120px" style="max-width: 500px;">
              <el-form-item label="当前密码" prop="current_password">
                <el-input type="password" v-model="passwordForm.current_password" show-password />
              </el-form-item>
              <el-form-item label="新密码" prop="new_password">
                <el-input type="password" v-model="passwordForm.new_password" show-password />
              </el-form-item>
              <el-form-item label="确认新密码" prop="new_password_confirmation">
                <el-input type="password" v-model="passwordForm.new_password_confirmation" show-password />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">确认修改密码</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="收货地址" name="addresses">
            <div class="address-management">
              <div class="toolbar">
                <el-button type="primary" :icon="EditPenIcon" @click="handleAddAddress">添加新地址</el-button>
              </div>

              <div v-if="loadingAddresses" class="tab-loading">
                <el-progress :percentage="50" :indeterminate="true" />
                <p>加载收货地址...</p>
              </div>
              <el-alert v-else-if="errorAddresses" :title="errorAddresses" type="error" show-icon :closable="false" />
              <el-empty v-else-if="!userAddresses.length" description="您还没有保存任何收货地址。"></el-empty>
              
              <div v-else class="address-list">
                <el-card v-for="addr in userAddresses" :key="addr.id" class="address-card" shadow="hover">
                  <template #header>
                    <div class="address-card-header">
                      <span>{{ addr.address_label || '地址' }}</span>
                      <el-tag v-if="addr.is_default_shipping" type="success" size="small">默认地址</el-tag>
                    </div>
                  </template>
                  <p><strong>收件人:</strong> {{ addr.recipient_name }}</p>
                  <p><strong>联系电话:</strong> {{ addr.phone_number }}</p>
                  <p>
                    <strong>地址:</strong> 
                    {{ addr.province }}{{ addr.city }}{{ addr.district }} {{ addr.street_address }}
                    <span v-if="addr.postal_code"> (邮编: {{ addr.postal_code }})</span>
                  </p>
                  <template #footer>
                    <div class="address-card-footer">
                        <el-button 
                            text 
                            type="primary" 
                            @click="handleSetDefault(addr)" 
                            :disabled="addr.is_default_shipping || settingDefaultId === addr.id"
                            :loading="settingDefaultId === addr.id"
                        >
                            设为默认
                        </el-button>
                        <el-button text type="primary" :icon="EditIcon" @click="handleEditAddress(addr)">编辑</el-button>
                        <el-button text type="danger" :icon="DeleteIcon" @click="handleDeleteAddress(addr)" :loading="deletingAddressId === addr.id">删除</el-button>
                    </div>
                  </template>
                </el-card>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>

        <!-- Add/Edit Address Dialog -->
        <el-dialog 
          v-model="dialogVisible" 
          :title="isEditMode ? '编辑收货地址' : '添加新收货地址'" 
          width="600px"
          :before-close="handleCloseDialog"
          append-to-body
          destroy-on-close
        >
          <el-form ref="addressFormRef" :model="currentAddressForm" :rules="addressRules" label-width="100px">
            <el-form-item label="收件人" prop="recipient_name">
              <el-input v-model="currentAddressForm.recipient_name" placeholder="收件人姓名" />
            </el-form-item>
            <el-form-item label="联系电话" prop="phone_number">
              <el-input v-model="currentAddressForm.phone_number" placeholder="手机号码" />
            </el-form-item>
            <el-form-item label="省份" prop="province">
              <el-input v-model="currentAddressForm.province" placeholder="例如：广东省" />
            </el-form-item>
            <el-form-item label="城市" prop="city">
              <el-input v-model="currentAddressForm.city" placeholder="例如：深圳市" />
            </el-form-item>
            <el-form-item label="区/县" prop="district">
              <el-input v-model="currentAddressForm.district" placeholder="例如：南山区 (可选)" />
            </el-form-item>
            <el-form-item label="详细地址" prop="street_address">
              <el-input v-model="currentAddressForm.street_address" type="textarea" placeholder="街道、楼牌号等" />
            </el-form-item>
            <el-form-item label="邮政编码" prop="postal_code">
              <el-input v-model="currentAddressForm.postal_code" placeholder="邮政编码 (可选)" />
            </el-form-item>
            <el-form-item label="地址标签" prop="address_label">
              <el-input v-model="currentAddressForm.address_label" placeholder="例如：家, 公司 (可选)" />
            </el-form-item>
            <el-form-item label="设为默认">
              <el-switch v-model="currentAddressForm.is_default_shipping" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmitAddressForm" :loading="submittingAddress">{{ isEditMode ? '保存修改' : '确认添加' }}</el-button>
          </template>
        </el-dialog>

      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import authService from '../api/auth.service';
import addressService from '../api/address.service'; // Import address service
import { ElMessage, ElMessageBox } from 'element-plus';
import { EditPen as EditPenIcon, Edit as EditIcon, Delete as DeleteIcon } from '@element-plus/icons-vue'; // Import icons

const activeTab = ref('info');

// --- Profile Info --- 
const currentUser = ref({ username: '', email: '', nickname: '' });
const profileForm = reactive({ nickname: '' });
const profileFormRef = ref(null);
const loadingProfile = ref(true);
const updatingProfile = ref(false);
const errorProfile = ref(null);

const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 50, message: '昵称长度在 1 到 50 个字符', trigger: 'blur' }
  ]
};

const fetchUserProfile = async () => {
  loadingProfile.value = true;
  errorProfile.value = null;
  try {
    const response = await authService.getCurrentUser();
    currentUser.value = response.data; // Assuming API returns { data: { id, username, email, nickname ...} }
    profileForm.nickname = currentUser.value.nickname;
  } catch (err) {
    console.error('获取用户信息失败:', err);
    errorProfile.value = err.message || '获取用户信息失败';
  } finally {
    loadingProfile.value = false;
  }
};

const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return;
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      updatingProfile.value = true;
      try {
        await authService.updateProfile({ nickname: profileForm.nickname });
        ElMessage.success('昵称更新成功！');
        await fetchUserProfile(); // Refresh user info
      } catch (err) {
        console.error('更新昵称失败:', err);
        ElMessage.error(err.response?.data?.message || err.message || '更新昵称失败');
      } finally {
        updatingProfile.value = false;
      }
    }
  });
};

// --- Password Change --- 
const passwordFormRef = ref(null);
const passwordForm = reactive({
  current_password: '',
  new_password: '',
  new_password_confirmation: ''
});
const changingPassword = ref(false);

const validatePassConfirm = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'));
  } else if (value !== passwordForm.new_password) {
    callback(new Error('两次输入的新密码不一致'));
  } else {
    callback();
  }
};

const passwordRules = {
  current_password: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少为8位', trigger: 'blur' } // Add more rules as needed
  ],
  new_password_confirmation: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validatePassConfirm, trigger: 'blur' }
  ]
};

const handleChangePassword = async () => {
  if (!passwordFormRef.value) return;
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      changingPassword.value = true;
      try {
        await authService.updatePassword({
          current_password: passwordForm.current_password,
          new_password: passwordForm.new_password,
          new_password_confirmation: passwordForm.new_password_confirmation
        });
        ElMessage.success('密码修改成功！请重新登录。'); // Typically, password change invalidates current session/token
        // Clear token and redirect to login
        localStorage.removeItem('user_token');
        router.push({ name: 'Login' }); 
        // Or, if backend doesn't invalidate token automatically, you might not need to force re-login
        // passwordFormRef.value.resetFields(); // Clear form
      } catch (err) {
        console.error('修改密码失败:', err);
        ElMessage.error(err.response?.data?.message || err.message || '修改密码失败');
      } finally {
        changingPassword.value = false;
      }
    }
  });
};

// --- Address Management ---
const userAddresses = ref([]);
const loadingAddresses = ref(true);
const errorAddresses = ref(null);
const dialogVisible = ref(false);
const isEditMode = ref(false);
const currentAddressForm = reactive({
  id: null,
  recipient_name: '',
  phone_number: '',
  street_address: '',
  city: '',
  district: '',
  province: '',
  postal_code: '',
  country: '中国', // Default
  is_default_shipping: false,
  address_label: ''
});
const addressFormRef = ref(null);
const submittingAddress = ref(false);
const settingDefaultId = ref(null); // To show loading on specific set default button
const deletingAddressId = ref(null); // To show loading on specific delete button

const addressRules = {
  recipient_name: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
  phone_number: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  province: [{ required: true, message: '请输入省份', trigger: 'blur' }],
  city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
  street_address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
};

const fetchAddresses = async () => {
  loadingAddresses.value = true;
  errorAddresses.value = null;
  try {
    const response = await addressService.getAddresses();
    userAddresses.value = response.data; // API returns { data: [...] }
  } catch (err) {
    console.error('获取收货地址失败:', err);
    errorAddresses.value = err.message || '获取收货地址失败';
  } finally {
    loadingAddresses.value = false;
  }
};

const resetCurrentAddressForm = () => {
  currentAddressForm.id = null;
  currentAddressForm.recipient_name = '';
  currentAddressForm.phone_number = '';
  currentAddressForm.street_address = '';
  currentAddressForm.city = '';
  currentAddressForm.district = '';
  currentAddressForm.province = '';
  currentAddressForm.postal_code = '';
  currentAddressForm.country = '中国';
  currentAddressForm.is_default_shipping = false;
  currentAddressForm.address_label = '';
  if(addressFormRef.value) {
    addressFormRef.value.resetFields(); // Clear validation states
  }
};

const handleAddAddress = () => {
  isEditMode.value = false;
  resetCurrentAddressForm();
  dialogVisible.value = true;
};

const handleEditAddress = (address) => {
  isEditMode.value = true;
  // Directly assign, or deep clone if needed to avoid reactivity issues with original list item
  Object.assign(currentAddressForm, address);
  dialogVisible.value = true;
};

const handleCloseDialog = (done) => {
  // Can add confirmation if form is dirty
  resetCurrentAddressForm();
  done();
};

const handleSubmitAddressForm = async () => {
  if (!addressFormRef.value) return;
  await addressFormRef.value.validate(async (valid) => {
    if (valid) {
      submittingAddress.value = true;
      try {
        const payload = { ...currentAddressForm };
        if (isEditMode.value && payload.id) {
          await addressService.updateAddress(payload.id, payload);
          ElMessage.success('地址修改成功！');
        } else {
          // Remove id if it exists for new address creation
          const { id, ...newAddressPayload } = payload;
          await addressService.addAddress(newAddressPayload);
          ElMessage.success('新地址添加成功！');
        }
        dialogVisible.value = false;
        await fetchAddresses(); // Refresh list
      } catch (err) {
        console.error('保存地址失败:', err);
        ElMessage.error(err.response?.data?.message || err.message || '操作失败');
      } finally {
        submittingAddress.value = false;
      }
    }
  });
};

const handleSetDefault = async (address) => {
  if (address.is_default_shipping) return;
  settingDefaultId.value = address.id;
  try {
    await addressService.setDefaultAddress(address.id);
    ElMessage.success(`地址 "${address.address_label || address.recipient_name}" 已设为默认`);
    await fetchAddresses(); // Refresh list
  } catch (err) {
    console.error('设置默认地址失败:', err);
    ElMessage.error(err.response?.data?.message || err.message || '设置默认地址失败');
  } finally {
    settingDefaultId.value = null;
  }
};

const handleDeleteAddress = async (address) => {
  ElMessageBox.confirm(
    `确定要删除地址 "${address.address_label || address.recipient_name}" 吗？此操作不可撤销。`,
    '确认删除',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    deletingAddressId.value = address.id;
    try {
      await addressService.deleteAddress(address.id);
      ElMessage.success('地址删除成功！');
      await fetchAddresses(); // Refresh list
      // If the deleted address was default, the backend should handle clearing it,
      // or we might need to re-evaluate which address is now default.
    } catch (err) {
      console.error('删除地址失败:', err);
      ElMessage.error(err.response?.data?.message || err.message || '删除地址失败');
    } finally {
      deletingAddressId.value = null;
    }
  }).catch(() => {
    // User cancelled
  });
};

watch(activeTab, (newTab) => {
  if (newTab === 'addresses' && !userAddresses.value.length) { // Fetch only if not already populated or forced refresh needed
    fetchAddresses();
  }
});

onMounted(() => {
  fetchUserProfile();
  if (activeTab.value === 'addresses') { // If addresses tab is active on mount
      fetchAddresses();
  }
});

</script>

<style scoped>
.profile-container {
  padding: 20px;
}
.profile-tabs .el-tab-pane {
    padding: 15px;
}
.tab-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 150px;
}

/* Address Management Styles */
.address-management .toolbar {
  margin-bottom: 20px;
  text-align: right;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.address-card {
  /* transition: box-shadow 0.3s; */
}

.address-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.address-card p {
  margin: 8px 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.address-card strong {
  color: #303133;
}

.address-card .el-card__footer {
    padding: 10px 15px;
    background-color: #f9f9f9;
}

.address-card-footer {
  text-align: right;
}

.address-card-footer .el-button + .el-button {
    margin-left: 8px;
}
</style> 